package com.fili.gui.sources;

import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import java.awt.*;

/**
 * Created by Claudiu-Florin FILIMON
 * Date: Nov 17, 2006
 * Time: 1:24:40 PM
 * Revision: 0
 */
public class LineNumbers extends JComponent
{
    private JTextPane textPane;
    private JScrollPane scrollPane;


    public LineNumbers(JTextPane textPane, JScrollPane scrollPane)
    {
        this.textPane = textPane;
        this.scrollPane = scrollPane;
    }

    protected void paintComponent(Graphics g)
    {
        g.setColor(getBackground());
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor(Color.black);
        setFont(new Font("Monospaced", Font.PLAIN, 12));

        int start = textPane.viewToModel(scrollPane.getViewport().getViewPosition());
        int end = textPane.viewToModel(new Point(
                scrollPane.getViewport().getViewPosition().x + textPane.getWidth(),
                scrollPane.getViewport().getViewPosition().y + textPane.getHeight()));

        Document doc = textPane.getDocument();
        int startline = doc.getDefaultRootElement().getElementIndex(start) + 1;
        int endline = doc.getDefaultRootElement().getElementIndex(end) + 1;

        int fontHeight = g.getFontMetrics(textPane.getFont()).getHeight();
        int fontDesc = g.getFontMetrics(textPane.getFont()).getDescent();
        int starting_y = -1;

        try
        {
            starting_y = textPane.modelToView(start).y - scrollPane.getViewport().getViewPosition().y + fontHeight - fontDesc;
        }
        catch (BadLocationException e1)
        {
            e1.printStackTrace();
        }

        FontMetrics lm = g.getFontMetrics();

        for (int line = startline, y = starting_y; line <= endline; y += fontHeight, line++)
        {
            String txt = Integer.toString(line);
            g.drawString(txt, getWidth() - lm.stringWidth(txt) - 3, y);
        }
    }


    public Dimension getPreferredSize()
    {
        return new Dimension(50, 50);
    }
}
